package com.zchu.rxcache.utils;


import ohos.hiviewdfx.HiLog;
import ohos.hiviewdfx.HiLogLabel;

import java.security.PublicKey;
import java.util.Collection;
import java.util.Iterator;

/**
 * Util class to print the log into the format
 *
 * @author 赵成柱
 * @since 2021-02-09
 */
public final class LogUtils {

    private static final String TAG_LOG = "--RxCache--";

    private static final int DOMAIN_ID = 0xD000F00;

    public static final HiLogLabel LABEL_LOG = new HiLogLabel(3, DOMAIN_ID, LogUtils.TAG_LOG);

    private static final String LOG_FORMAT = "%{public}s: %{public}s";

    private LogUtils() {
    }

    public static boolean DEBUG = false;

    public static void log(Object message) {
        StackTraceElement element = new Throwable().getStackTrace()[1];
        print(element, message, null);
    }

    public static void log(Object message, Throwable error) {
        StackTraceElement element = new Throwable().getStackTrace()[1];
        print(element, message, error);
    }

    public static void debug(Object message) {
        if (DEBUG) {
            StackTraceElement element = new Throwable().getStackTrace()[1];
            print(element, message, null);
        }
    }

    public static void debug(Object message, Throwable error) {
        if (DEBUG) {
            StackTraceElement element = new Throwable().getStackTrace()[1];
            print(element, message, error);
        }
    }


    private static void print(StackTraceElement element, Object message, Throwable error) {
        String className = element.getClassName();
        className = className.substring(className.lastIndexOf('.') + 1);
        String tag = className + '.' + element.getMethodName() + '(' + element.getFileName() + ':' + element.getLineNumber() + ')';
        String text = toString(message);

        if (error != null) {

            HiLog.error(LABEL_LOG, LOG_FORMAT, tag, "\n\t" + error);
        } else {
            HiLog.error(LABEL_LOG, LOG_FORMAT, tag, "\n\t" + text);

        }
    }

    private static String toString(Object message) {
        if (message == null) {
            return "[null]";
        }
        if (message instanceof Throwable) {
            return HiLog.getStackTrace((Throwable) message);
        }
        if (message instanceof Collection) {
            return toString((Collection) message);
        }
        return String.valueOf(message);
    }

    private static String toString(Collection message) {
        Iterator it = message.iterator();
        if (!it.hasNext())
            return "[]";

        StringBuilder sb = new StringBuilder();
        sb.append('[');
        for (; ; ) {
            Object e = it.next();
            sb.append(e);
            if (!it.hasNext())
                return sb.append(']').toString();
            sb.append(",\n ");
        }
    }

}
